﻿using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace STX.Repository
{
    /// <summary>
    /// Class DataBaseContext.
    /// </summary>
    public class DataBaseContext:DbContext
    {

        /// <summary>
        /// Class ReportingDbMigrationsConfiguration.
        /// </summary>
        internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<DataBaseContext>
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="ReportingDbMigrationsConfiguration"/> class.
            /// </summary>
            public ReportingDbMigrationsConfiguration()
            {
                AutomaticMigrationsEnabled = true;//任何Model Class的修改將會直接更新DB
                AutomaticMigrationDataLossAllowed = true;
            }
        }

        #region 静态构造方法
        /// <summary>
        /// 初始化
        /// </summary>
        static DataBaseContext()
        {
            //自动创建表，如果Entity有改到就更新到表结构
            Database.SetInitializer<DataBaseContext>(
                   new MigrateDatabaseToLatestVersion<DataBaseContext, ReportingDbMigrationsConfiguration>());   
        }
        #endregion

        #region 构造方法
        /// <summary>
        /// 初始化
        /// </summary>
        public DataBaseContext()
            : base("Name=Default")
        {
           
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="nameOrConnectionString">数据库连接</param>
        public DataBaseContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
           
        }
        
        #endregion

        #region 创建实体模型
        /// <summary>
        /// 创建实体模型
        /// </summary>
        /// <param name="modelBuilder">实体模型生成器</param>
        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            new Mapping().RegisterTo(modelBuilder);
        }
        #endregion
    }
}
